package com.mijie.homi.api;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.mijie.core.ApplicationProperties;
import com.mijie.core.Status;
import com.mijie.homi.common.constant.HomiConstants;
import com.mijie.homi.common.constant.HomiStatusCode;
import com.mijie.homi.common.domain.user.User;
import com.mijie.homi.common.util.HomiUtil;
import com.mijie.homi.domain.album.Album;
import com.mijie.homi.domain.album.Photo;
import com.mijie.homi.service.album.AlbumService;
import com.mijie.homi.service.common.CommentService.COMMENT;
import com.mijie.homi.service.common.ReplyService.REPLY;
import com.mijie.homi.service.user.PrivacyService;
import com.mijie.homi.service.user.UserExtInfoService;
import com.mijie.homi.service.user.UserService;
import com.mijie.homi.util.ServerHelper;
import com.mijie.util.FileUploadUtil;
import com.mijie.util.IOUtil;
import com.mijie.util.ImageUtil;

@Controller
@RequestMapping("/album")
public class AlbumApi extends CommomApi{

	@Autowired
	private AlbumService albumService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserExtInfoService userExtInfoService;
	@Autowired
	private PrivacyService privacyService;
	
	private Logger logger = Logger.getLogger(AlbumApi.class);
	
	@RequestMapping(value="/cover/setting",method=RequestMethod.POST)
	public @ResponseBody void settingCover(HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		Integer userId = ServerHelper.getUserId(request);
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		JSONObject json = JSONObject.fromObject(content);
		String image = json.getString("image");
		Status status = new Status(request,response);
		if(image!=null){
			int rows = userExtInfoService.settingAlbumCover(userId, image);
			if(rows==0)
				status.setCode(HomiStatusCode.API_EXCEPTION);
		}else{
			status.setCode(HomiStatusCode.PARAM_ABSENT);
		}
		status.write();
	}
	
	@RequestMapping(value="/cover/upload",method=RequestMethod.POST)
	public @ResponseBody void uploadCover(MultipartHttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		
		Status status = new Status(request,response);
		MultipartFile file  = request.getFile("image");
		if(file==null){
			status.setCode(HomiStatusCode.PARAM_ABSENT);
			status.write();
			return;
		}
		
		if(!FileUploadUtil.validate(file, HomiConstants.IMAGE_SUFFIX)){
			status.setCode(HomiStatusCode.UPLOAD_FILE_ILLEGAL);
			status.write();
			return;
		}
		if(file.getSize()>HomiConstants.IMAGE_MAX_SIZE){
			status.setCode(HomiStatusCode.UPLOAD_FILE_SIZE_LIMIT);
			status.write();
			return;
		}
		
		
		String imageHome = ApplicationProperties.get("album.cover.home");
		String savePath = ApplicationProperties.get("resource.path")+imageHome;
		Integer userId = ServerHelper.getUserId(request);
		
		String imageName = FileUploadUtil.upload(file, savePath);
		
		if(imageName!=null){
			int rows = userExtInfoService.settingAlbumCover(userId, imageHome+imageName);
			if(rows==0) status.setCode(HomiStatusCode.API_EXCEPTION);
			else
				status.setResult("{\"path\":\""+HomiUtil.getRealUrl(imageHome+imageName)+"\"}");
		}else{
			status.setCode(HomiStatusCode.UPLOAD_FILE_FAIL);
		}
		
		status.write();
	}
	
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public @ResponseBody void upload(MultipartHttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		Integer userId = ServerHelper.getUserId(request);
		String describes = request.getParameter("describes");
		if(describes==null) describes = ""; else describes = describes.trim();
		
		
		Status status = new Status(request,response);
		if(describes.length()>HomiConstants.MAX_WORD_PHOTO_DESCRIBE){
			status.setCode(HomiStatusCode.CONTENT_LENGTH_LIMIT);
			status.write();
			return;
		}
		
		
		String imageSmallHome = ApplicationProperties.get("album.small.home");
		String imageLargeHome = ApplicationProperties.get("album.large.home");
		String basePath = ApplicationProperties.get("resource.path");
		Photo photo = null;
		MultipartFile file = null;
		Iterator<String> fileNames = request.getFileNames();
		List<Photo> photoList = new ArrayList<Photo>();
		String name = null;
		while(fileNames.hasNext()){
			name = fileNames.next();
			file = request.getFile(name);
			if(file!=null && file.getSize()>0){
				
				if(!FileUploadUtil.validate(file, HomiConstants.IMAGE_SUFFIX)){
					status.setCode(HomiStatusCode.UPLOAD_FILE_ILLEGAL);
					continue;
				}
				if(file.getSize()>HomiConstants.IMAGE_MAX_SIZE){
					status.setCode(HomiStatusCode.UPLOAD_FILE_SIZE_LIMIT);
					continue;
				}
				
				String imageName = FileUploadUtil.upload(file, basePath+imageLargeHome);
				File src = new File(basePath+imageLargeHome+imageName);
				if(src.exists()){
					File dest = new File(basePath+imageSmallHome+imageName);
					ImageUtil.zoomWithFixWidth(src, dest, 150, 0);
					photo = new Photo();
					photo.setIdx(Long.MAX_VALUE-System.currentTimeMillis());
					photo.setUserId(userId);
					photo.setCreateAt(new Date());
					photo.setSmallImage(imageSmallHome+imageName);
					photo.setLargeImage(imageLargeHome+imageName);
					photoList.add(photo);
				}else{
					throw new IOException("Album upload photo fail.");
				}
				
			}
			fileNames.remove();
		}
		if(photoList.size()>0){
			int rows = albumService.uploadPhoto(userId,describes,photoList);
			if(rows==0) status.setCode(HomiStatusCode.API_EXCEPTION);
		}else{
			status.setCode(HomiStatusCode.PARAM_ABSENT);
		}
		status.write();
	}
	
	@RequestMapping(value="/photo/get",method=RequestMethod.GET)
	public @ResponseBody void getPhoto(long id,HttpServletRequest request,HttpServletResponse response){
		Integer requester = ServerHelper.getUserId(request);
		Photo photo = albumService.getPhoto(id);
		Status status = new Status(request,response);
		if(photo!=null){
			User user = userService.getUserById(photo.getUserId());
			Album album = albumService.getAlbum(photo.getAlbumId());
			if(album!=null){
				JSONObject result = JSONObject.fromObject(photo);
				result.put("smallImage", HomiUtil.getRealUrl(photo.getSmallImage()));
				result.put("largeImage", HomiUtil.getRealUrl(photo.getLargeImage()));
				result.put("userAvatar", HomiUtil.getRealUrl(user.getAvatar()));
				result.put("userNickName", user.getNickName());
				result.put("albumDescribes", album.getDescribes());
				result.put("createAt", photo.getCreateAt().getTime());
				status.setResult(result);
			}else{
				status.setCode(HomiStatusCode.API_EXCEPTION);
			}
		}else{
			status.setCode(HomiStatusCode.RECORD_NOT_FOUND);
		}
		status.write();
	}
	
	@RequestMapping(value="/delete",method=RequestMethod.GET)
	public @ResponseBody void deleteAlbum(int id,HttpServletRequest request,HttpServletResponse response){
		Integer userId = ServerHelper.getUserId(request);
		int rows = albumService.deleteAlbum(id, userId);
		Status status = new Status(request,response);
		if(rows==0) status.setCode(HomiStatusCode.POSSESSION_ERROR);
		status.write();
	}
	
	@RequestMapping(value="/photo/delete",method=RequestMethod.GET)
	public @ResponseBody void deletePhoto(long id,HttpServletRequest request,HttpServletResponse response){
		Integer userId = ServerHelper.getUserId(request);
		Status status = new Status(request,response);
		Photo photo = albumService.getPhoto(id);
		if(photo!=null){
			int rows = albumService.deletePhoto(userId, id);
			if(rows==0){
				status.setCode(HomiStatusCode.POSSESSION_ERROR);
			}else{
				String basePath = ApplicationProperties.get("resource.path");
				File smallFile = new File(basePath+photo.getSmallImage());
				File largeFile = new File(basePath+photo.getLargeImage());
				if(smallFile.exists() && smallFile.isFile() && smallFile.getName().endsWith("jpg"))
					smallFile.delete();
					
				if(largeFile.exists() && largeFile.isFile() && largeFile.getName().endsWith("jpg"))
					largeFile.delete();
			}
		}else{
			status.setCode(HomiStatusCode.RECORD_NOT_FOUND);
		}
		status.write();
	}
	
	@RequestMapping(value="/photo/list/latest",method=RequestMethod.GET)
	public @ResponseBody void listLatestPhoto(int userId,int size,
			HttpServletRequest request,HttpServletResponse response){
		if(size<=0) size = 5;
		Integer requester = ServerHelper.getUserId(request);
		Status status = new Status(request,response);
		List<Photo> list = albumService.listLatestPhoto(userId, size);
		JSONArray result = new JSONArray();
		JSONObject json = null;
		Photo photo = null;
		Iterator<Photo> iter = list.iterator();
		while(iter.hasNext()){
			photo = iter.next();
			iter.remove();
			json = JSONObject.fromObject(photo);
			json.put("smallImage", HomiUtil.getRealUrl(photo.getSmallImage()));
			json.put("largeImage", HomiUtil.getRealUrl(photo.getLargeImage()));
			json.put("createAt", photo.getCreateAt().getTime());
			result.add(json);
		}
		iter = null;
		list = null;
		status.setResult(result);
		status.write();
	}
	
	@RequestMapping(value="/photo/like",method=RequestMethod.POST)
	public @ResponseBody void likePhoto(HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		String content = IOUtil.getContent4InputStream(request.getInputStream());
		JSONObject json = JSONObject.fromObject(content);
		int rows = albumService.likePhoto(json.getLong("id"));
		Status status = new Status(request,response);
		if(rows==0) status.setCode(HomiStatusCode.RECORD_NOT_FOUND);
		status.write();
	}
	
	@RequestMapping(value="/photo/list",method=RequestMethod.GET)
	public @ResponseBody void listPhoto(Integer userId,Long idx,Integer limit,
			HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		Status status = new Status(request,response);
		JSONArray result = new JSONArray();
		List<Album> albumIdList = albumService.listAlbum(userId, idx, limit);
		
		List<Photo> photoList = null;
		JSONObject albumJson = null;
		JSONObject photoJson = null;
		JSONArray photoArray =  null;
		Album album = null;
		Photo photo = null;
		Iterator<Album> albumIter = albumIdList.iterator();
		Iterator<Photo> photoIter = null;
		while(albumIter.hasNext()){
			album = albumIter.next();
			albumIter.remove();
			albumJson = new JSONObject();
			albumJson.accumulate("albumId", album.getId());
			albumJson.accumulate("albumIdx", album.getIdx());
			albumJson.accumulate("albumCreateAt", album.getCreateAt().getTime());
			albumJson.accumulate("albumDescribes", album.getDescribes());
			photoArray =  new JSONArray();
			photoList = albumService.listPhotoByAlbumId(album.getId());
			if(photoList.isEmpty()){
				albumService.deleteAlbum(album.getId(), userId);
				continue;
			}
			photoIter = photoList.iterator();
			while(photoIter.hasNext()){
				photo = photoIter.next();
				photoIter.remove();
				photoJson = JSONObject.fromObject(photo);
				photoJson.remove("id");
				photoJson.remove("idx");
				photoJson.accumulate("photoId", photo.getId());
				photoJson.put("createAt", photo.getCreateAt().getTime());
				photoJson.put("smallImage", HomiUtil.getRealUrl(photo.getSmallImage()));
				photoJson.put("largeImage", HomiUtil.getRealUrl(photo.getLargeImage()));
				photoArray.add(photoJson);
			}
			albumJson.accumulate("photos", photoArray);
			result.add(albumJson);
		}
		photoIter = null;
		photoList = null;
		albumIter = null;
		albumIdList = null;
		status.setResult(result);
		status.write();
	}
	
	@RequestMapping(value="/photos",method=RequestMethod.GET)
	public @ResponseBody void photos(int userId,Long idx,Integer limit,
			HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		Status status = new Status(request,response);
		JSONArray result = new JSONArray();
		List<Photo> photoList = albumService.listPhotoByUserId(userId, idx, limit);
		JSONObject photoJson = null;
		JSONArray photoArray =  null;
		Photo photo = null;
		Iterator<Photo> photoIter = photoList.iterator();
		while(photoIter.hasNext()){
			photo = photoIter.next();
			photoIter.remove();
			photoJson = JSONObject.fromObject(photo);
			photoJson.put("createAt", photo.getCreateAt().getTime());
			photoJson.put("smallImage", HomiUtil.getRealUrl(photo.getSmallImage()));
			photoJson.put("largeImage", HomiUtil.getRealUrl(photo.getLargeImage()));
			result.add(photoJson);
		}
		status.setResult(result);
		status.write();
	}
	
	@RequestMapping(value="/photo/comment/post",method=RequestMethod.POST)
	public @ResponseBody void postComment(HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		super.postComment(COMMENT.PHOTO, request, response);
	}
	
	@RequestMapping(value="/photo/comment/delete",method=RequestMethod.GET)
	public @ResponseBody void deleteComment(long id,long parentId,HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		super.deleteComment(COMMENT.PHOTO, id, parentId,request, response);
	}
	
	@RequestMapping(value="/photo/comment/admin/delete",method=RequestMethod.GET)
	public @ResponseBody void deleteCommentByAdmin(long id,long parentId,HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		super.deleteCommentByAdmin(COMMENT.PHOTO, id, parentId,request, response);
	}
	
	@RequestMapping(value="/photo/comment/list",method=RequestMethod.GET)
	public @ResponseBody void listPhotoComment(long idx,long targetId,int limit,HttpServletRequest request,HttpServletResponse response){
		super.listComment(COMMENT.PHOTO,idx, targetId, limit, request, response);
	}
	
	@RequestMapping(value="/photo/comment/reply/post",method=RequestMethod.POST)
	public @ResponseBody void postReply(HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		super.postReply(REPLY.PHOTO_COMMENT, request, response);
	}
	
	@RequestMapping(value="/photo/comment/reply/delete",method=RequestMethod.GET)
	public @ResponseBody void deleteReply(long id,long parentId,HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		super.deleteReply(REPLY.PHOTO_COMMENT,id, parentId,request, response);
	}
	
	@RequestMapping(value="/photo/comment/reply/admin/delete",method=RequestMethod.GET)
	public @ResponseBody void deleteReplyByAdmin(long id,long parentId,HttpServletRequest request,HttpServletResponse response) 
			throws IOException{
		super.deleteReplyByAdmin(REPLY.PHOTO_COMMENT,id, parentId,request, response);
	}
	
	@RequestMapping(value="/photo/comment/reply/list",method=RequestMethod.GET)
	public @ResponseBody void listReply(long idx,long targetId,int limit,HttpServletRequest request,HttpServletResponse response){
		super.listReply(REPLY.PHOTO_COMMENT,idx, targetId, limit, request, response);
	}

	@RequestMapping(value="/photo/review/post",method=RequestMethod.POST)
	public @ResponseBody void review(HttpServletRequest request,
			HttpServletResponse response) {
		super.review(this.albumService, request, response);
	}

	@RequestMapping(value="/photo/review/delete",method=RequestMethod.POST)
	public @ResponseBody void deleteReview(HttpServletRequest request,HttpServletResponse response) {
		super.deleteReview(this.albumService, request, response);
	}

	@RequestMapping(value="/photo/review/list",method=RequestMethod.GET)
	public @ResponseBody void listReview(long eventId, int offset,
			int limit, HttpServletRequest request, HttpServletResponse response) {
		super.listReview(this.albumService, eventId, offset, limit, request, response);
	}
	
}
